<template>
  <a-form
      :model="ruleForm"
      ref="ruleForm"
      v-bind="layout"
      :rules="rules"
      @finish="handleFinish"
  >
    <a-form-item label="课题名称" name="subject_name">
      <a-input v-model:value="ruleForm.subject_name"/>
    </a-form-item>
    <a-form-item label="课题类型" name="subject_type">
      <a-input v-model:value="ruleForm.subject_type"/>
    </a-form-item>
    <a-form-item label="关键词" name="subject_keyword">
      <a-input v-model:value="ruleForm.subject_keyword"/>
    </a-form-item>
    <a-form-item label="责任人" name="subject_principal">
      <a-select
          v-model:value="ruleForm.subject_principal"
          style="width: 120px"
          ref="select"
      >
        <a-select-option
            v-for="item in subject_principalSelectionOptions"
            :key="item.url"
        >
          {{ item.label }}
        </a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="参与人" name="targetsubject_participantKeys">
      <a-transfer
          :data-source="ruleForm.subject_participants"
          :titles="['未选择', '已选择']"
          :target-keys="ruleForm.targetsubject_participantKeys"
          :selected-keys="ruleForm.selectedsubject_participantKeys"
          :render="(item) => item.title"
          @change="handleChange"
          @selectChange="handleSelectChange"
          :locale="{
          itemUnit: '项',
          itemsUnit: '项',
          notFoundContent: '列表为空',
          searchPlaceholder: '请输入搜索内容',
        }"
      />
    </a-form-item>
    <!--    <a-form-item label="参与人" name="subject_participant">-->
    <!--      <a-select-->
    <!--        v-model:value="ruleForm.subject_participant"-->
    <!--        style="width: 120px"-->
    <!--        ref="select"-->
    <!--      >-->
    <!--        <a-select-option-->
    <!--          v-for="item in subject_participantSelectionOptions"-->
    <!--          :key="item.url"-->
    <!--        >-->
    <!--          {{ item.label }}-->
    <!--        </a-select-option>-->
    <!--      </a-select>-->
    <!--    </a-form-item>-->
    <!--    <a-form-item label="审核人" name="subject_reviewer">-->
    <!--      <a-select-->
    <!--        v-model:value="ruleForm.subject_reviewer"-->
    <!--        style="width: 120px"-->
    <!--        ref="select"-->
    <!--      >-->
    <!--        <a-select-option-->
    <!--          v-for="item in subject_reviewerSelectionOptions"-->
    <!--          :key="item.url"-->
    <!--        >-->
    <!--          {{ item.label }}-->
    <!--        </a-select-option>-->
    <!--      </a-select>-->
    <!--    </a-form-item>-->
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" :loading="submitting" html-type="submit">
        {{ submitting ? '提交中' : '确定' }}
      </a-button>
    </a-form-item>
  </a-form>
</template>
<script>
import {message} from 'ant-design-vue'

export default {
  name: 'AddorEditSubject',
  // url !== ''则为编辑操作，否则为添加
  props: ['url'],
  emits: ['operate-success', 'operate-failed'],
  data() {
    let validatesubject_principal = async (rule, value) => {
      if (value === "") {
        return Promise.reject("请选择课题负责人");
      }
    };
    let validatesubject_participant = async (rule, value) => {
      if (value.length === 0) {
        return Promise.reject('请选择课题参与人')
      }
    };

    return {
      ruleForm: {
        subject_name: '',
        subject_type: '',
        subject_keyword: '',
        subject_principal: '',
        subject_participants: [],
        targetsubject_participantKeys: [],
        selectedsubject_participantKeys: [],
        // subject_participant: '',
        // subject_reviewer : '',
      },
      rules: {
        subject_principal: [
          {
            validator: validatesubject_principal,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
        targetsubject_participantKeys: [
          {
            validator: validatesubject_participant,
            trigger: "change",
            required: true,
            whitespace: true,
          },
        ],
      },
      layout: {
        labelCol: {span: 4},
        wrapperCol: {span: 14},
      },
      submitting: false,
      subject_principalSelectionOptions: [],
      // subject_participantSelectionOptions: [],
      // subject_reviewerSelectionOptions: [],
      headers: {
        authorization: 'authorization-text',
      },
      // subject_participants: [],

    }
  },
  mounted() {
    this.fetch()
  },
  methods: {
    // 从后端获取数据
    fetch() {
      this.subject_principalSelectionOptions = []
      // this.subject_participantSelectionOptions = []
      // this.subject_reviewerSelectionOptions = []
      this.axios
          .get('/user_management/users')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.subject_principalSelectionOptions.push({
                url: data[i].url,
                label: data[i].username,
              })
            }
          })
      this.axios
          .get('/user_management/users')
          .then((res) => {
            const data = res.data
            for (let i = 0; i < data.length; ++i) {
              this.ruleForm.subject_participants.push({
                key: data[i].url,
                title: data[i].username,
                // url: data[i].url,
                // label: data[i].username,
              })
            }
            // })
            // this.axios
            // .get('/user_management/users')
            // .then((res) => {
            //   const data = res.data
            //   for (let i = 0; i < data.length; ++i) {
            //     this.subject_reviewerSelectionOptions.push({
            //       url: data[i].url,
            //       label: data[i].username,
            //     })
            //   }
            this.ruleForm.username = data.length === 0 ? '' : data[0].url
            if (this.url !== '') {
              this.axios
                  .get(this.url)
                  .then((res) => {
                    const data = res.data
                    this.ruleForm.subject_name = data.subject_name
                    this.ruleForm.subject_type = data.subject_type
                    this.ruleForm.subject_keyword = data.subject_keyword
                    this.ruleForm.subject_principal = data.subject_principal
                    this.ruleForm.targetsubject_participantKeys = data.subject_participant
                    // this.ruleForm.subject_participant = data.subject_participant
                    // this.ruleForm.subject_reviewer = data.subject_principal
                  })
                  .catch((error) => {
                    console.log('Error', error.message)
                  })
            }
          })
          .catch((error) => {
            console.log('Error', error.message)
            this.ruleForm.college_name = ''
          })
    },
    handleFinish(values) {
      this.submitting = true
      const formData = new FormData()
      formData.append('subject_name', values.subject_name)
      formData.append('subject_type', values.subject_type)
      formData.append('subject_keyword', values.subject_keyword)
      formData.append('subject_principal', values.subject_principal)
      // formData.append('subject_participant', values.subject_participant)
      this.ruleForm.targetsubject_participantKeys.forEach((subject_participant) => {
        // console.log('test', subject_participant)
        formData.append("subject_participant", subject_participant);
      })
      // formData.append('subject_participant', values.subject_participant)
      // formData.append('subject_reviewer', values.subject_principal)
      // if (this.targetsubject_participantKeys===''){
      //   return Promise.reject('请选择参与人！')
      // }
      if (this.url !== '') {
        this.axios
            .put(this.url, formData)
            .then(() => {
              this.submitting = false
              message.success('修改成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('修改失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      } else {
        this.axios
            .post('/subject_management/subjects/', formData)
            .then(() => {
              this.submitting = false
              message.success('添加成功！')
              this.$emit('operate-success')
            })
            .catch((error) => {
              this.submitting = false
              message.error('添加失败！')
              this.$emit('operate-failed')
              console.log('Error', error.message)
            })
      }
    },
    handleChange(nextTargetKeys) {
      this.ruleForm.targetsubject_participantKeys = nextTargetKeys
    },
    handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
      this.ruleForm.selectedsubject_participantKeys = [
        ...sourceSelectedKeys,
        ...targetSelectedKeys,
      ]
      // console.log('sourceSelectedKeys: ', sourceSelectedKeys)
      // console.log('targetSelectedKeys: ', targetSelectedKeys)
    },
  },
}
</script>
